/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao (cnfree2000@hotmail.com) ***/
package com.wang.myapplication.tools;


import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtils {
    private static Map<String, Retrofit> mRetrofitMap = new HashMap();


    public static Retrofit getRetrofitInstance(String baseUrl) {
        Retrofit result = null;
        synchronized (RetrofitUtils.class) {
            Retrofit retrofit = (Retrofit) mRetrofitMap.get(baseUrl);
            if (retrofit == null) {
                //声明日志类
                HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
                //设定日志级别
                httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                //自定义OkHttpClient
                OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
                //添加拦截器
                okHttpClient.addInterceptor(httpLoggingInterceptor);


                //创建并指定自定义的OkHttpClient
                retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .client(okHttpClient.build())//此行为了log
                        .build();

                mRetrofitMap.put(baseUrl, retrofit);
            }
            result = retrofit;
        }
        return result;
    }

    public static <T> T createApi(String baseUrl, Class<T> clazz) {
        Retrofit retrofit = getRetrofitInstance(baseUrl);
        return retrofit.create(clazz);
    }


    public static <T> Call<T> enqueue(Call<T> call, Callback<T> callback) {
        if (call != null) {
            call.enqueue(callback);
        }
        return call;
    }

    public static <T> void cancel(Call<T> call) {
        if (call != null)
            call.cancel();
    }
}